package org.glut.cloud.materialManage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.glut.cloud.materialManage.entity.MaterialChange;
import org.glut.cloud.materialManage.entity.MaterialPurchases;
import org.glut.cloud.materialManage.entity.MaterialsManage;
import org.glut.cloud.materialManage.mapper.MaterialChangeMapper;
import org.glut.cloud.materialManage.mapper.MaterialPurchasesMapper;
import org.glut.cloud.materialManage.mapper.MaterialsManageMapper;
import org.glut.cloud.materialManage.service.IMaterialPurchasesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 材料采购表 服务实现类
 *
 * @author sanminzhi
 * @since 2024-07-19 11:26
 */
@Service
public class MaterialPurchasesServiceImpl extends ServiceImpl<MaterialPurchasesMapper, MaterialPurchases> implements IMaterialPurchasesService {

    @Autowired
    private MaterialPurchasesMapper materialPurchasesMapper;

    @Autowired
    private MaterialsManageMapper materialsManageMapper;

    @Autowired
    private MaterialChangeMapper materialChangeMapper;


    @Override
    @Transactional
    public MaterialPurchases saveMaterialPurchases(MaterialPurchases materialPurchases){
        materialPurchases.setRequestTime(new Date());

        boolean result = saveOrUpdate(materialPurchases);
        if (!result) {
            throw new RuntimeException("申请购买材料失败");
        }
        return materialPurchases;
    }


    @Override
    public List<MaterialPurchases> getPurchases() {
        LambdaQueryWrapper<MaterialPurchases> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.isNull(MaterialPurchases::getAgreedTime);
        return list(queryWrapper);
    }


    @Override
    @Transactional
    public boolean agreePurchase(MaterialPurchases materialPurchases) {
        materialPurchases.setAgreed("是");
        materialPurchases.setAgreedTime(new java.sql.Timestamp(System.currentTimeMillis()));

        LambdaQueryWrapper<MaterialsManage> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MaterialsManage::getMaterialName, materialPurchases.getMaterialName());
        MaterialsManage existingMaterial = materialsManageMapper.selectOne(queryWrapper);

        if (existingMaterial != null) {
            existingMaterial.setQuantity(existingMaterial.getQuantity() + materialPurchases.getPurchaseQuantity());
            materialsManageMapper.updateById(existingMaterial);
        } else {
            MaterialsManage newMaterial = MaterialsManage.builder()
                    .materialName(materialPurchases.getMaterialName())
                    .materialDescription(materialPurchases.getMaterialDescription())
                    .category(materialPurchases.getCategory())
                    .quantity(materialPurchases.getPurchaseQuantity())
                    .build();
            materialsManageMapper.insert(newMaterial);
            existingMaterial = newMaterial;
        }

        // 记录库存变动（增加）
        MaterialChange record = new MaterialChange();
        record.setMaterialId(existingMaterial != null ? existingMaterial.getMaterialId() : null); // 如果是新建物料，id 可能为 null
        record.setMaterialName(materialPurchases.getMaterialName());
        record.setChangeQuantity(materialPurchases.getPurchaseQuantity()); // 增加数量
        record.setChangeTime(new java.sql.Timestamp(System.currentTimeMillis()));
        record.setChangeType("增加");
        materialChangeMapper.insert(record);

        int result = materialPurchasesMapper.updateById(materialPurchases);
        return result > 0;
    }


    @Override
    public boolean rejectPurchase(MaterialPurchases materialPurchases) {
        materialPurchases.setAgreed("否");
        materialPurchases.setAgreedTime(new java.sql.Timestamp(System.currentTimeMillis()));
        int result = materialPurchasesMapper.updateById(materialPurchases);
        return result > 0;
    }


    @Override
    public List<MaterialPurchases> getRecentAgreedPurchases() {
        LambdaQueryWrapper<MaterialPurchases> queryWrapper = new LambdaQueryWrapper<>();
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.DAY_OF_YEAR, -7);
        Date sevenDaysAgo = calendar.getTime();
        queryWrapper.ge(MaterialPurchases::getAgreedTime, sevenDaysAgo);
        return list(queryWrapper);
    }


    @Override
    public void updateMaterialQuantity(String materialName, int quantity) {
        materialPurchasesMapper.updateMaterialQuantity(materialName, quantity);
    }

}
